﻿using clf.weighing.entity;
using HandyControl.Controls;
using MyHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms.VisualStyles;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using UserControl = System.Windows.Controls.UserControl;
using Panel = System.Windows.Controls.Panel;
using RadioButton = System.Windows.Controls.RadioButton;
using Control = System.Windows.Controls.Control;
using CheckBox = System.Windows.Controls.CheckBox;
using Button = System.Windows.Controls.Button;
using ComboBox = System.Windows.Controls.ComboBox;
using TextBox = System.Windows.Controls.TextBox;
using MessageBox = HandyControl.Controls.MessageBox;

namespace weighing
{
    /// <summary>
    /// SinpleWeighingUc.xaml 简易过磅 的交互逻辑
    /// </summary>
    public partial class SimpleWeighingUc : UserControl
    {

        #region variables
        private bool isOutFactory = false;
        /// <summary>
        /// 是否为 委托事件传入的数据
        /// </summary>
        private bool isDelegeteSelectData = false;

        private System.Timers.Timer? mTimer;
        /// <summary>
        /// 读取磅称的是否提示
        /// </summary>
        private bool isSaleAlert = true;
        private double currTonner = 0;
        /// <summary>
        /// 数据是否是已经存在，二次过磅还不完成的情况
        /// </summary>
        private bool isBillExist = false;
        private bool isSetDefaultValue = false;
        #endregion

        #region pro
        private WeighingBill _bill;


        public WeighingBill mWeighingBill
        {
            get
            {
                if (_bill == null)
                {
                    _bill = new WeighingBill()
                    {
                        id = IdHelper.LongID,
                        type = (int)WeightingBillType.Mixture,
                        isDelete = 0,
                        deleteReason = "",
                        dataType = (int)DataType.Prod,
                        unitText = CommonFunction.GetUnitText(),
                        affiliatedCompanyId = App.CurrentCompanyVo?.Id ?? 0,
                        upGovernmentStatus = 0,
                        upOfficalStatus = 0,
                    };
                }
                return _bill;
            }
        }

        #endregion

        public SimpleWeighingUc()
        {
            InitializeComponent();
            if (DesignerProperties.GetIsInDesignMode(this)) return;
            isOutFactory = false;

            DelegeteFactory.Instance.onSimpleWeighingSelectOutData += OnSimpleWeighingSelectOutDataHandle;
            DelegeteFactory.Instance.OnBackupBillFieldChanged += OnBackupBillFieldChangedHandle;
        }

        #region event

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            InitInputUi();

            UpdateUIFontSize();

            string number = BillNumberHelper.GetWeighingNumber(WeightingBillType.Mixture);
            this.billnumberTb.Text = number;
            mWeighingBill.number = number;
            SetWeihinger();

            //将本机使用的基础数据设置默认数据源 
            SetDefaultSource();

            SetDefaultValue();

            CreateBackFillUI();

            SetAllBackFieldItemSource();

            InitTimer();

            mTimer?.Start();
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            mTimer?.Stop();
            mTimer?.Dispose();
        }
        #endregion

        private void InitTimer()
        {
            mTimer = new System.Timers.Timer(1000);
            mTimer.BeginInit();
            mTimer.Elapsed += (obj, args) =>
            {
                this.Dispatcher.Invoke(new Action(delegate
                {
                    ReadScaleData();
                }));
            };
            mTimer.EndInit();
        }

        private void SetDefaultValue()
        {
            isSetDefaultValue = true;
            //times
            if (App.Config.WeighingConfig.Times == 2)
            {
                this.TwiceRb.IsChecked = true;
            }
            else if (App.Config.WeighingConfig.Times == 1)
            {
                this.OnceRb.IsChecked = true;
            }
            else
            {
                this.TwiceRb.IsChecked = true;
            }
            this.ignoreTraeWeightCb.IsChecked = App.Config.WeighingConfig.InIgnoreTraeWeighing;
            isSetDefaultValue = false;
        }
        /// <summary>
        /// 读取磅称数据 
        /// </summary>
        private void ReadScaleData()
        {
            MainWindow? mw = App.Current.MainWindow as MainWindow;
            ScaleVo? vo = mw?.ScaleContentUc.GetCurrentScale(WeightingBillType.Buy);

            if (vo == null)
            {
                string msg = "没有指定磅秤\n请点击上方的磅称，或者去设置默认";
                if (isSaleAlert)
                {
                    var result = CommonFunction.Ask(msg);
                    if (result == MessageBoxResult.Yes)
                    {
                        isSaleAlert = false;
                    }
                }
                return;
            }
            int digits = App.Config.WeighingConfig.Digits;
            var tonner = vo.Tonner;
            currTonner = tonner;

            if (App.Config.WeighingConfig.Times == 2)
            {
                if (this.isGrossRb.IsChecked == true)
                {
                    this.grossWeightTb.Text = tonner.ToString();
                }
                if (this.isTraceRb.IsChecked == true)
                {
                    this.TraeWeightTb.Text = tonner.ToString();
                }
            }
            else
            {
                if (App.Config.WeighingConfig.InIgnoreTraeWeighing)
                {
                    this.netWeightTb.Text = tonner.ToString();
                }
                else
                {
                    this.grossWeightTb.Text = tonner.ToString();
                }
            }
        }
        private void OnSimpleWeighingSelectOutDataHandle(WeighingBill bill)
        {
            if (bill != null && bill.status != (int)BillStatus.Finished)
            {
                isOutFactory = true;

                _bill = bill;

                BindValue(bill);

                if (_bill.grossWeight <= 0)
                {
                    this.isGrossRb.IsChecked = true;
                }
                else
                {
                    this.grossWeightTb.Text = bill.grossWeight?.ToString() ?? "0.0";
                }

                if (_bill.traeWeight <= 0)
                {
                    this.isTraceRb.IsChecked = true;
                }
                else
                {
                    this.TraeWeightTb.Text = bill.traeWeight?.ToString() ?? "0.0";
                }
                //设置车牌号 不再去查找
                isDelegeteSelectData = true;

                this.carNumberCb.Text = _bill.carNumber;

                isDelegeteSelectData = false;

                isOutFactory = false;
            }
        }

        #region 将本机使用的基础数据设置默认数据源 最新使用的排在最前面
        /// <summary>
        /// 将本机使用的基础数据设置默认数据源 
        /// </summary>
        private void SetDefaultSource()
        {
            var companyS = CompanyDao.Instance.GetList().Select(i => { return new CompanyVo(i); }).ToList();
            var ms = MaterialDao.Instance.GetList().Select(i => { return new MaterialVo(i); }).ToList();
            var cars = CarDao.Instance.GetList().Select(i => { return new CarInfoVo(i); }).ToList();
            this.sendCompanyCb.ItemsSource = companyS;
            this.RecevieCompanyCb.ItemsSource = companyS;
            this.materialCb.ItemsSource = ms;
            this.carNumberCb.ItemsSource = cars;
            this.sendCompanyCb.SelectedIndex = -1;
            this.RecevieCompanyCb.SelectedIndex = -1;
            this.materialCb.SelectedIndex = -1;
            this.carNumberCb.SelectedIndex = -1;

            CommonFunction.SetRemarkItemSource(this.remarkCb);
        }

        #endregion


        #region Supply         
        private void SupplyCb_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
        private void SupplyCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sendCompanyCb.SelectedIndex == -1)
            {
                this.sendCompanyCb.Text = "";
                return;
            }

        }

        #endregion


        #region Receiver Company

        private void ReceiverCompanyCb_TextChanged(object sender, TextChangedEventArgs e)
        {
        }
        private void ReceiverCompanyCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (RecevieCompanyCb.SelectedIndex == -1)
            {
                RecevieCompanyCb.Text = "";
                return;
            };
        }

        #endregion

        #region Material 

        private void MaterialNameCb_TextChanged(object sender, TextChangedEventArgs e)
        {

        }   

        private void MaterialNameCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (materialCb.SelectedIndex > -1)
            {
                //SetMaterialPrice();

            }

        }
        #endregion

        #region CarInfo Selection       
        private void CarNumberCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            String text = this.carNumberCb.Text.Trim();
            if (isDelegeteSelectData) return;
            if (this.carNumberCb.SelectedIndex > -1) return;
            if (text.Length > 2)
            {
                Task.Delay(200).ContinueWith((t) =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        GetNoOutBill(text);
                    });
                });
            }
            if (text.Length <= 0) this.carNumberCb.SelectedIndex = -1;
        }

        private void CarNumberCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!IsLoaded) return;

            if (carNumberCb.SelectedIndex >= 0)
            {
                CarInfoVo? currCarVo = carNumberCb.SelectedItem as CarInfoVo;
                SetCarInfo(currCarVo);
                if (App.Config.WeighingConfig.Times == 2)
                {
                    GetNoOutBill(currCarVo?.CarNumber ?? "");
                }

                if (string.IsNullOrEmpty(this.driverTb.Text))
                {
                    this.driverTb.Text = currCarVo?.Driver ?? "";
                }

                if (string.IsNullOrEmpty(this.phoneTb.Text))
                {
                    this.phoneTb.Text = currCarVo?.DriverMobile ?? "";
                }
            }
            else
            {
                ResertUI(false);
            }
        }

        private void SetCarInfo(CarInfoVo? car)
        {
            if (car != null)
            {
                this.driverTb.Text = car.Driver;
                this.phoneTb.Text = car.DriverMobile;
                if (App.Config.WeighingConfig.Times == 1 && !App.Config.WeighingConfig.InIgnoreTraeWeighing)
                {
                    this.TraeWeightTb.Text = car.TraeWeight?.ToString() ?? "0";
                }
            }
            else
            {
                this.driverTb.Text = string.Empty;
                this.phoneTb.Text = string.Empty;
                this.TraeWeightTb.Text = "0";
            }
        }


        private bool isGetNoOut = false;
        /// <summary>
        /// 获取未完成的磅单
        /// </summary>
        private void GetNoOutBill(string carNumber)
        {
            if (isGetNoOut == true) { return; }
            this.isGetNoOut = true;

            if (string.IsNullOrWhiteSpace(carNumber))
            {
                this.isGetNoOut = false;
                return;
                //throw new ArgumentException($"“{nameof(carNumber)}”不能为 null 或空白。", nameof(carNumber));
            }
            //获取最后未完成的数据.
            //1.如果当前是过毛，就获取最后一有皮重，未完成的数据 
            //2.如果当前是过皮，就获取最后一有毛重，未完成的数据 
            bool isGross = this.isTraceRb.IsChecked == true ? false : true;
            //WeighingBill bill =  WeighingBillDao.Instance.FindLastNoFinishByWeight(carNumber, isGross);
            //先找到数据，再根据数据切换过毛过皮，也可以人工切换
            WeighingBill? bill = WeighingBillDao.Instance.FindLastNoFinish(carNumber);
            isBillExist = bill != null;
            if (bill != null)
            {
                _bill = bill;

                if (bill.grossWeight <= 0)
                {
                    this.isGrossRb.IsChecked = true;
                }
                else
                {
                    this.isTraceRb.IsChecked = true;
                }

                BindValue(bill);

                isDelegeteSelectData = true;

                this.carNumberCb.Text = bill.carNumber;

                isDelegeteSelectData = false;

                isOutFactory = true;
            }
            else
            {
                _bill = null;
                this.billnumberTb.Text = BillNumberHelper.GetWeighingNumber(WeightingBillType.Mixture);
                isOutFactory = false;
                ResertUI(false);
            }

            this.isGetNoOut = false;
        }

        private void BindValue(WeighingBill bill)
        {
            isBillExist = bill != null;
            if (bill == null) return;
            this.billnumberTb.Text = bill.number?.ToString() ?? "";
            this.sendCompanyCb.Text = bill.sendCompanyName?.ToString() ?? "";
            this.RecevieCompanyCb.Text = bill.receiveCompanyName?.ToString() ?? "";
            this.materialCb.Text = bill.materialName?.ToString() ?? "";
            this.driverTb.Text = bill.driver?.ToString() ?? "";
            this.phoneTb.Text = bill.driverMobile?.ToString() ?? "";
            this.remarkCb.Text = bill.remark?.ToString() ?? "";

            if (bill.grossWeight > 0)
            {
                this.grossWeightTb.Text = bill.grossWeight?.ToString() ?? "0";
            }
            if (bill.traeWeight > 0)
            {
                this.TraeWeightTb.Text = bill.traeWeight?.ToString() ?? "0";
            }
            SetBackFieldValue();
            this.TempPriceTb.Text = mWeighingBill?.price.ToString() ?? "0";
            this.TotalMoneyTb.Text = mWeighingBill?.totalMoney?.ToString() ?? "0";
            this.ReceiveMoneyTb.Text = mWeighingBill?.receiveMoney.ToString() ?? "0";
            this.MoneyTypeCb.SelectedIndex = (mWeighingBill?.moneyType) ?? 0;
        }
        #endregion

        #region Weihinger
        private void SetWeihinger()
        {
            this.userTb.Text = App.CurrentUser.name;
            this.userTb.Text = App.CurrentUser.name;
        }
        #endregion

        #region remark

        private void RemardTbox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (IsLoaded == false) { return; }
            string value = this.remarkCb.Text;
        }
        #endregion

        private void GrossWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcReceiptWeightValue();
        }

        private void TraeWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcReceiptWeightValue();
        }

        /// <summary>
        /// 计算收货吨位  calculating the tonnage of receipt
        /// </summary>
        private void CalcReceiptWeightValue()
        {
            if (this.IsLoaded == false || this.IsVisible == false) return;

            decimal gross = 0;
            decimal trae = 0;
            decimal decuation = 0;
            decimal net = 0;
            decimal sendnet = 0;
            decimal diff;
            try { gross = Convert.ToDecimal(this.grossWeightTb.Text); } catch { }
            try { trae = Convert.ToDecimal(this.TraeWeightTb.Text); } catch { }

            if (trae > 0)
            {
                net = gross - trae - decuation;
                this.netWeightTb.Text = net.ToString();
            }
            else
            {
                this.netWeightTb.Text = "0";
            }
            diff = Math.Round(net - sendnet, 2);
            //this.diffWeightTb.Text = diff.ToString();

        }

        /// <summary>
        /// 获取稳重的数据
        /// </summary>
        private void GetWeightValue()
        {
            if (this.IsLoaded == false || this.IsVisible == false) return;

            decimal gross = 0;
            decimal trae = 0;
            decimal decuation = 0;
            decimal net = 0;
            decimal sendnet = 0;
            try { gross = Convert.ToDecimal(this.grossWeightTb.Text); } catch { }
            try { trae = Convert.ToDecimal(this.TraeWeightTb.Text); } catch { }
            try { net = Convert.ToDecimal(this.netWeightTb.Text); } catch { }

            decimal diff = Math.Round(net - sendnet, 2);

            mWeighingBill.grossWeight = gross;
            mWeighingBill.traeWeight = trae;
            mWeighingBill.decuationWeight = decuation;
            mWeighingBill.netWeight = net;
            mWeighingBill.diffWeight = diff;
        }

        public void ReLayout()
        {
            //基本上不用做处理

        }

        #region save

        private bool isSaving = false;

        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isSaving) return;
            isSaving = true;
            GetWeightValue();

            GetBackFieldValue();

            GetPriceValue();

            mWeighingBill.sendCompanyId = 0;
            mWeighingBill.sendCompanyName = this.sendCompanyCb.Text;
            mWeighingBill.receiveCompanyId = 0;
            mWeighingBill.receiveCompanyName = this.RecevieCompanyCb.Text;

            mWeighingBill.materialId = 0;
            mWeighingBill.materialName = this.materialCb.Text;

            mWeighingBill.carId = 0;
            mWeighingBill.carNumber = this.carNumberCb.Text;
            mWeighingBill.driver = this.driverTb.Text;
            mWeighingBill.driverMobile = this.phoneTb.Text;
            mWeighingBill.remark = this.remarkCb.Text;
            if (mWeighingBill.number.IsNullOrEmpty())
            {
                mWeighingBill.number = this.billnumberTb.Text;
            }

            if (mWeighingBill.number.IsNullOrEmpty())
            {
                var msg = "系统出错，请重启称重系统，再试。";
                Growl.Clear();
                Growl.Error(msg, "main");
                this.saveBtn.IsChecked = false;
                isSaving = false;
                return;
            }
            //只要有一个重量大于0 ，就是正常的过磅
            if (mWeighingBill.grossWeight <= 0 && mWeighingBill.traeWeight <= 0 && mWeighingBill.netWeight <= 0)
            {
                var msg = "未读取重量";
                Growl.Clear();
                Growl.Error(msg, "main");
                this.saveBtn.IsChecked = false;
                isSaving = false;
                return;
            }

            if (isOutFactory)
            {
                mWeighingBill.outTime = DateTime.Now;
                //入场默认为皮
                mWeighingBill.outUserName = App.CurrentUser?.name;
            }
            else
            {
                mWeighingBill.addTime = DateTime.Now;
                mWeighingBill.inTime = mWeighingBill.addTime;
                mWeighingBill.addUserId = App.CurrentUser?.Id;
                mWeighingBill.addUserName = App.CurrentUser?.name;

                //入场默认为毛
                mWeighingBill.inUserName = App.CurrentUser?.name;
            }

            mWeighingBill.houseId = App.CurrentScaleHouseVo?.Id ?? 0;
            mWeighingBill.houseName = App.CurrentScaleHouseVo?.Name ?? "";

            if (mWeighingBill.netWeight == mWeighingBill.grossWeight
                || mWeighingBill.netWeight == mWeighingBill.traeWeight
                || mWeighingBill.netWeight <= 0)
            {
                mWeighingBill.status = (int)BillStatus.NoOut;
                mWeighingBill.inTime = DateTime.Now;
            }
            else
            {
                if (mWeighingBill.netWeight > 0 && mWeighingBill.traeWeight > 0 && mWeighingBill.grossWeight > 0)
                {
                    //所有重必须大于0方为完成
                    mWeighingBill.status = (int)BillStatus.Finished;
                    mWeighingBill.outTime = DateTime.Now;
                }
                else
                {
                    mWeighingBill.status = (int)BillStatus.NoOut;
                    mWeighingBill.inTime = DateTime.Now;
                }
            }
            if (App.Config.WeighingConfig.Times == 1)
            {
                mWeighingBill.status = (int)BillStatus.Finished;
            }
            if (mWeighingBill.status == (int)BillStatus.Finished)
            {
                var tone = App.Config.WeighingConfig.MixedValidTone;
                var minTone = App.Config.WeighingConfig.Unit == Unit.Tone ? tone : (tone * 1000);
                if (mWeighingBill.netWeight <= minTone)
                {
                    var msg = "净重吨位错误";
                    Growl.Clear();
                    Growl.Error(msg, "main");
                    this.saveBtn.IsChecked = false;
                    isSaving = false;
                    return;
                }
            }

            mWeighingBill.affiliatedCompanyId = App.CurrentCompanyVo?.Id;
            int res = -1;
            if (App.Config.WeighingConfig.Times == 2)
            {
                //状态为完成 更新，未完成有数据更新，无数据插入
                res = mWeighingBill.status == (int)BillStatus.Finished
               ? WeighingBillDao.Instance.Update(mWeighingBill)
               : isBillExist ? WeighingBillDao.Instance.Update(mWeighingBill) : WeighingBillDao.Instance.Insert(mWeighingBill);
            }
            else
            {
                mWeighingBill.status = (int)BillStatus.Finished;
                mWeighingBill.inTime = DateTime.Now;
                mWeighingBill.outTime = mWeighingBill.inTime;
                res = WeighingBillDao.Instance.Insert(mWeighingBill);
            }

            var info = "";
            int status = mWeighingBill?.status ?? 0;
            long id = mWeighingBill?.id ?? 0;
            if (res > 0)
            {
                Growl.Clear();
                info = "保存成功";
                Growl.Success(info, "main");

                SaveRemark(this.remarkCb.Text);

                AsyncSaveBaseData();

                ResertUI(true);

                DelegeteFactory.Instance.onWeighingDataChanged?.Invoke(WeightingBillType.Mixture);
                this.saveBtn.IsChecked = false;

                if (status == (int)BillStatus.Finished)
                {
                    ToPrint(id);
                }
            }
            else
            {
                info = "保存失败";
                Growl.Error(info, "main");
            }
            isBillExist = false;
            this.saveBtn.IsChecked = false;
            isSaving = false;
        }

        #endregion


        private void ToPrint(long id)
        {
            if (App.Config.BillPrintConfig.IsUserExclCustomBill)
            {
                new PrintEXCLWindow(id).ShowDialog();
            }
            else
            {
                new PrintWindow(id, WeightingBillType.WeighintBill).ShowDialog();
            }
        }

        private void ResertBtn_Click(object sender, RoutedEventArgs e)
        {
            // 重 置
            this.carNumberCb.SelectedIndex = -1;
            isOutFactory = false;
            isDelegeteSelectData = false;
            this.saveBtn.IsChecked = false;

            ResertUI(true);
            SetDefaultSource();
        }

        private void AsyncSaveBaseData()
        {
            _ = AsyncFactory.Instance.SaveCarAsync(mWeighingBill?.carNumber ?? "", mWeighingBill?.driver ?? "", mWeighingBill?.driverMobile ?? "");
            _ = AsyncFactory.Instance.SaveCompanyAsync(mWeighingBill?.sendCompanyName ?? "");
            _ = AsyncFactory.Instance.SaveCompanyAsync(mWeighingBill?.receiveCompanyName ?? "");
            _ = AsyncFactory.Instance.SaveMaterialAsync(mWeighingBill?.materialName ?? "");
            var cbs = this.backFieldPanel.Children.OfType<ComboBox>().ToList();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (var b in cbs)
            {
                if (!string.IsNullOrEmpty(b.Text))
                {
                    dic.Add(b.Name, b.Text);
                }
            }
            _ = UpdateBackupFieldComboBoxItemSourceAsync(dic);

            AddBackupFiledItemSource();
        }

        private void SaveRemark(string remark)
        {
            if (remark.IsNullOrEmpty()) return;
            string key = "OutputReamak";
            var itemsource = GlobalData.GetAllItemSource();
            var ris = itemsource != null ? (itemsource.Keys.Contains(key) ? itemsource[key] : null) : null;
            if (ris != null)
            {
                if (!ris.Contains(remark))
                {
                    ris.Add(remark);
                    itemsource[key] = ris;
                }
            }
            else
            {
                ris = new List<string> { remark };
                if (itemsource.Keys.Contains(key))
                {
                    itemsource[key] = ris;
                }
                else
                {
                    itemsource.Add(key, ris);
                }
            }
            this.remarkCb.ItemsSource = null;
            this.remarkCb.ItemsSource = ris;
        }

        private void ResertUI(bool clearCar)
        {
            this._bill = null;
            this.billnumberTb.Text = BillNumberHelper.GetWeighingNumber(WeightingBillType.Mixture);
            if (clearCar)
            {
                this.carNumberCb.Text = string.Empty;
            }
            this.driverTb.Text = string.Empty;
            this.phoneTb.Text = string.Empty;
            this.sendCompanyCb.Text = string.Empty;
            this.RecevieCompanyCb.Text = string.Empty;
            this.materialCb.Text = string.Empty;
            this.remarkCb.Text = string.Empty;
            this.grossWeightTb.Text = "0";
            this.TraeWeightTb.Text = "0";
            this.netWeightTb.Text = "0";
            this.TempPriceTb.Text = "0";
            this.TotalMoneyTb.Text = "0";
            this.ReceiveMoneyTb.Text = "0";
            this.MoneyTypeCb.SelectedIndex = 0;
            ResertBackFieldValue();
            isOutFactory = false;
        }

        #region 车牌号输入

        private void KeyBoardBtn_Click(object sender, RoutedEventArgs e)
        {
            this.carInputPopup.IsOpen = !this.carInputPopup.IsOpen;
            if (this.carInputPopup.IsOpen)
            {
                this.carNumberInput.Complated += On_Complated;
            }
            else
            {
                this.carNumberInput.Complated -= On_Complated;
            }
        }

        private void On_Complated(string res)
        {
            this.carNumberCb.Text = res;
            this.carInputPopup.IsOpen = false;
        }
        #endregion

        #region Gross Trae  Rb _ Checked
        private void IsTraceRb_Checked(object sender, RoutedEventArgs e)
        {
            if (IsLoaded == false) return;
            var rb = sender as RadioButton;
            if (rb != null)
            {
                string t = rb.Tag?.ToString() ?? "";
                this.saveBtn.Content = t;
            }
            if (isOutFactory)
            {
                if (mWeighingBill.grossWeight > 0)
                {
                    this.grossWeightTb.Text = mWeighingBill?.grossWeight?.ToString() ?? "0";
                }
                else
                {
                    this.grossWeightTb.Text = "0";
                }
            }
            else
            {
                this.grossWeightTb.Text = "0";
            }
        }

        private void IsGrossRb_Checked(object sender, RoutedEventArgs e)
        {
            if (IsLoaded == false) return;
            var rb = sender as RadioButton;
            if (rb != null)
            {
                string t = rb.Tag?.ToString() ?? "";
                this.saveBtn.Content = t;
            }
            if (isOutFactory)
            {
                if (mWeighingBill.traeWeight > 0)
                {
                    this.TraeWeightTb.Text = mWeighingBill?.traeWeight?.ToString() ?? "0";
                }
                else
                {
                    this.TraeWeightTb.Text = "0";
                }
            }
            else
            {
                this.TraeWeightTb.Text = "0";
            }
        }


        #endregion

        #region backup filed

        /// <summary>
        /// 修改创建 备用字段的UI
        /// </summary>
        private void CreateBackFillUI()
        {
            List<BackupBillField> backupBills = BackupBillFieldDao.Instance.SelectAllByType(mWeighingBill.type);
            if (backupBills == null || backupBills.Count == 0)
            {
                this.backFieldPanel.Children.Clear();
            }
            else
            {
                this.backFieldPanel.Children.Clear();
                int fontSize = App.Config.OtherConfig.SimpleWeighingUiFontSize;
                for (int i = 0; i < backupBills.Count; i++)
                {
                    var item = backupBills[i];
                    int w = item.width < 200 ? 200 : item.width;
                    w = item.width > 400 ? 400 : item.width;
                    if (item.isEnable == 1)
                    {
                        if (item.controlType == (int)BackFieldControlType.Combox)
                        {
                            var combobox = new System.Windows.Controls.ComboBox()
                            {
                                Name = item.fiedName + "CB",
                                Style = FindResource("ComboBoxExtend") as Style,
                                Margin = new Thickness(0, 2, 0, 2),
                                HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                                MinWidth = 100,
                                MaxWidth = 400,
                                Width = w,
                                MaxDropDownHeight = 300,
                                IsEditable = true,
                                FontSize = fontSize
                            };
                            InfoElement.SetTitle(combobox, item.displayName);
                            InfoElement.SetTitlePlacement(combobox, HandyControl.Data.TitlePlacementType.Left);
                            InfoElement.SetTitleWidth(combobox, new GridLength(Convert.ToDouble(item.titleWidth)));
                            this.backFieldPanel.Children.Add(combobox);
                        }
                        else
                        {
                            var textBox = new TextBox()
                            {
                                Name = item.fiedName + "TB",
                                Style = FindResource("TextBoxExtend") as Style,
                                Margin = new Thickness(0, 2, 0, 2),
                                HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                                MinWidth = 100,
                                MaxWidth = 400,
                                Width = w,
                                FontSize = fontSize,
                            };
                            InfoElement.SetTitle(textBox, item.displayName);
                            InfoElement.SetTitlePlacement(textBox, HandyControl.Data.TitlePlacementType.Left);
                            InfoElement.SetTitleWidth(textBox, new GridLength(Convert.ToDouble(item.titleWidth)));

                            this.backFieldPanel.Children.Add(textBox);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 设置备用字段的值
        /// </summary>
        private bool SetBackFieldValue()
        {
            if (this.backFieldPanel.Children.Count == 0) return true;
            for (int i = 0; i < this.backFieldPanel.Children.Count; i++)
            {
                try
                {
                    var child = this.backFieldPanel.Children[i] as System.Windows.Controls.TextBox;
                    if (child != null)
                    {
                        var name = child.Name.Replace("TB", "");
                        if (name == Constant.BackfieldName.BackString1)
                        {
                            child.Text = mWeighingBill.backupString1;
                        }
                        else if (name == Constant.BackfieldName.BackString2)
                        {
                            child.Text = mWeighingBill.backupString2;
                        }
                        else if (name == Constant.BackfieldName.BackString3)
                        {
                            child.Text = mWeighingBill.backupString3;
                        }
                        else if (name == Constant.BackfieldName.BackString4)
                        {
                            child.Text = mWeighingBill.backupString4;
                        }
                        else if (name == Constant.BackfieldName.BackString5)
                        {
                            child.Text = mWeighingBill.backupString5;
                        }
                        else if (name == Constant.BackfieldName.BackInt1)
                        {
                            child.Text = mWeighingBill.backupInt1.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackInt2)
                        {
                            child.Text = mWeighingBill.backupInt2.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackInt3)
                        {
                            child.Text = mWeighingBill.backupInt3.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackInt4)
                        {
                            child.Text = mWeighingBill.backupInt4.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackInt5)
                        {
                            child.Text = mWeighingBill.backupInt5.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackDecimal1)
                        {
                            child.Text = mWeighingBill.backupDecimal1.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackDecimal2)
                        {
                            child.Text = mWeighingBill.backupDecimal2.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackDecimal3)
                        {
                            child.Text = mWeighingBill.backupDecimal3.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackDecimal4)
                        {
                            child.Text = mWeighingBill.backupDecimal4.ToString();
                        }
                        else if (name == Constant.BackfieldName.BackDecimal5)
                        {
                            child.Text = mWeighingBill.backupDecimal5.ToString();
                        }
                    }
                    else
                    {
                        //child is null means control is  ComboBox
                        var cb = this.backFieldPanel.Children[i] as System.Windows.Controls.ComboBox;
                        if (cb != null)
                        {
                            var name = cb.Name.Replace("CB", "");
                            if (name == Constant.BackfieldName.BackString1)
                            {
                                cb.Text = mWeighingBill.backupString1;
                            }
                            else if (name == Constant.BackfieldName.BackString2)
                            {
                                cb.Text = mWeighingBill.backupString2;
                            }
                            else if (name == Constant.BackfieldName.BackString3)
                            {
                                cb.Text = mWeighingBill.backupString3;
                            }
                            else if (name == Constant.BackfieldName.BackString4)
                            {
                                cb.Text = mWeighingBill.backupString4;
                            }
                            else if (name == Constant.BackfieldName.BackString5)
                            {
                                cb.Text = mWeighingBill.backupString5;
                            }
                            else if (name == Constant.BackfieldName.BackInt1)
                            {
                                cb.Text = mWeighingBill.backupInt1.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackInt2)
                            {
                                cb.Text = mWeighingBill.backupInt2.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackInt3)
                            {
                                cb.Text = mWeighingBill.backupInt3.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackInt4)
                            {
                                cb.Text = mWeighingBill.backupInt4.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackInt5)
                            {
                                cb.Text = mWeighingBill.backupInt5.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackDecimal1)
                            {
                                cb.Text = mWeighingBill.backupDecimal1.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackDecimal2)
                            {
                                cb.Text = mWeighingBill.backupDecimal2.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackDecimal3)
                            {
                                cb.Text = mWeighingBill.backupDecimal3.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackDecimal4)
                            {
                                cb.Text = mWeighingBill.backupDecimal4.ToString();
                            }
                            else if (name == Constant.BackfieldName.BackDecimal5)
                            {
                                cb.Text = mWeighingBill.backupDecimal5.ToString();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Growl.Error("输入有错：" + ex.Message);
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 获取备用字段的值
        /// </summary>
        private bool GetBackFieldValue()
        {
            if (this.backFieldPanel.Children.Count == 0) return true;
            for (int i = 0; i < this.backFieldPanel.Children.Count; i++)
            {
                try
                {
                    var child = this.backFieldPanel.Children[i] as System.Windows.Controls.TextBox;
                    if (child != null)
                    {
                        var name = child.Name.Replace("TB", "");
                        if (name == Constant.BackfieldName.BackString1)
                        {
                            mWeighingBill.backupString1 = child.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString2)
                        {
                            mWeighingBill.backupString2 = child.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString3)
                        {
                            mWeighingBill.backupString3 = child.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString4)
                        {
                            mWeighingBill.backupString4 = child.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackString5)
                        {
                            mWeighingBill.backupString5 = child.Text?.Trim();
                        }
                        else if (name == Constant.BackfieldName.BackInt1)
                        {

                            mWeighingBill.backupInt1 = Convert.ToInt32(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt2)
                        {

                            mWeighingBill.backupInt2 = Convert.ToInt32(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt3)
                        {
                            mWeighingBill.backupInt3 = Convert.ToInt32(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt4)
                        {

                            mWeighingBill.backupInt4 = Convert.ToInt32(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackInt5)
                        {
                            mWeighingBill.backupInt5 = Convert.ToInt32(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal1)
                        {
                            mWeighingBill.backupDecimal1 = Convert.ToDecimal(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal2)
                        {
                            mWeighingBill.backupDecimal2 = Convert.ToDecimal(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal3)
                        {
                            mWeighingBill.backupDecimal3 = Convert.ToDecimal(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal4)
                        {
                            mWeighingBill.backupDecimal4 = Convert.ToDecimal(child.Text.Trim());
                        }
                        else if (name == Constant.BackfieldName.BackDecimal5)
                        {
                            mWeighingBill.backupDecimal5 = Convert.ToDecimal(child.Text.Trim());
                        }
                    }
                    else
                    {
                        var cb = this.backFieldPanel.Children[i] as System.Windows.Controls.ComboBox;
                        if (cb != null)
                        {
                            var name = cb.Name.Replace("CB", "");
                            string value = cb.Text?.Trim();
                            if (name == Constant.BackfieldName.BackString1)
                            {
                                mWeighingBill.backupString1 = value;
                            }
                            else if (name == Constant.BackfieldName.BackString2)
                            {
                                mWeighingBill.backupString2 = value;
                            }
                            else if (name == Constant.BackfieldName.BackString3)
                            {
                                mWeighingBill.backupString3 = value;
                            }
                            else if (name == Constant.BackfieldName.BackString4)
                            {
                                mWeighingBill.backupString4 = value;
                            }
                            else if (name == Constant.BackfieldName.BackString5)
                            {
                                mWeighingBill.backupString5 = value;
                            }
                            else if (name == Constant.BackfieldName.BackInt1)
                            {

                                mWeighingBill.backupInt1 = Convert.ToInt32(value);
                            }
                            else if (name == Constant.BackfieldName.BackInt2)
                            {

                                mWeighingBill.backupInt2 = Convert.ToInt32(value);
                            }
                            else if (name == Constant.BackfieldName.BackInt3)
                            {
                                mWeighingBill.backupInt3 = Convert.ToInt32(value);
                            }
                            else if (name == Constant.BackfieldName.BackInt4)
                            {

                                mWeighingBill.backupInt4 = Convert.ToInt32(value);
                            }
                            else if (name == Constant.BackfieldName.BackInt5)
                            {
                                mWeighingBill.backupInt5 = Convert.ToInt32(value);
                            }
                            else if (name == Constant.BackfieldName.BackDecimal1)
                            {
                                mWeighingBill.backupDecimal1 = Convert.ToDecimal(value);
                            }
                            else if (name == Constant.BackfieldName.BackDecimal2)
                            {
                                mWeighingBill.backupDecimal2 = Convert.ToDecimal(value);
                            }
                            else if (name == Constant.BackfieldName.BackDecimal3)
                            {
                                mWeighingBill.backupDecimal3 = Convert.ToDecimal(value);
                            }
                            else if (name == Constant.BackfieldName.BackDecimal4)
                            {
                                mWeighingBill.backupDecimal4 = Convert.ToDecimal(value);
                            }
                            else if (name == Constant.BackfieldName.BackDecimal5)
                            {
                                mWeighingBill.backupDecimal5 = Convert.ToDecimal(value);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Growl.Error("输入有错：" + ex.Message, "edit");
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 重置备用字段的值
        /// </summary>
        private bool ResertBackFieldValue()
        {
            if (this.backFieldPanel.Children.Count == 0) return true;
            for (int i = 0; i < this.backFieldPanel.Children.Count; i++)
            {
                try
                {
                    var child = this.backFieldPanel.Children[i] as System.Windows.Controls.TextBox;
                    if (child != null)
                    {
                        var name = child.Name.Replace("TB", "");
                        child.Text = string.Empty;
                    }
                    else
                    {
                        var cb = this.backFieldPanel.Children[i] as System.Windows.Controls.ComboBox;
                        if (cb != null)
                        {
                            var name = cb.Name.Replace("CB", "");
                            cb.Text = string.Empty;
                            cb.SelectedIndex = -1;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Growl.Error("输入有错：" + ex.Message, "main");
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// Set all ComboBox ItemSource
        /// </summary>
        private void SetAllBackFieldItemSource()
        {
            var items = GlobalData.GetAllItemSource();
            if (items == null || items.Count == 0) return;
            List<ComboBox> cbs = new List<ComboBox>();
            var childs = backFieldPanel.Children;
            for (int i = 0; i < childs.Count; i++)
            {
                if (childs[i] is ComboBox cb)
                {
                    //名称与 backup 开头的，TextBox 才是备用字段
                    if (cb.Name.StartsWith("backup")) cbs.Add(cb);
                }
            }
            if (cbs.Count == 0) return;

            foreach (ComboBox cb in cbs)
            {
                string key = cb.Name;
                var itemSource = items.ContainsKey(key) ? items[key] : null;
                cb.ItemsSource = itemSource;
            }
        }



        /// <summary>
        /// Set ComboBox ItemSource
        /// </summary>
        /// <param name="cb"></param>
        private void SetComboBoxBackupFieldItemSource(ComboBox cb)
        {
            if (cb == null) return;
            var items = GlobalData.GetAllItemSource();
            if (items == null || items.Count == 0) return;

            string key = cb.Name;
            var itemSource = items.ContainsKey(key) ? items[key] : null;

            cb.ItemsSource = null;
            cb.ItemsSource = itemSource;
        }

        private async Task<bool> UpdateBackupFieldComboBoxItemSourceAsync(Dictionary<string, string> dic)
        {
            return await Task<bool>.Factory.StartNew(() =>
            {
                var itemSource = GlobalData.GetAllItemSource();
                itemSource ??= new Dictionary<string, List<string>>();
                foreach (var kv in dic)
                {
                    if (itemSource.Keys.Contains(kv.Key))
                    {
                        var list = itemSource[kv.Key];
                        if (!list.Contains(kv.Value))
                        {
                            list.Add(kv.Value);
                            itemSource[kv.Key] = list;
                        }
                    }
                    else
                    {
                        itemSource.Add(kv.Key, new List<string>() { kv.Value });
                    }
                }

                //update
                if (itemSource != null && itemSource.Count > 0)
                {
                    BackupItemsHelper.Instance.UpdateToFile(itemSource);
                }

                return true;
            });
        }


        private void AddBackupFiledItemSource()
        {
            //update combox dispacher to main thread
            var cbs = this.backFieldPanel.Children.OfType<ComboBox>().ToList();
            if (cbs == null || cbs.Count == 0) return;
            foreach (var cb in cbs)
            {
                SetComboBoxBackupFieldItemSource(cb);
            }
        }
        #endregion

        public void OnBackupBillFieldChangedHandle(BackupBillField backupBillField)
        {
            //备用字段改变
            if (backupBillField.billType == (int)WeightingBillType.Mixture)
            {
                CreateBackFillUI();
                //becus CreateBackFillUI() function clear the backupPanel's children
                SetAllBackFieldItemSource();
            }

        }

        #region price calc
        private void NetWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcMaterialMoney();
        }
        private void TempPriceTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcMaterialMoney();
        }
        /// <summary>
        /// 计算货物的金额
        /// </summary>
        private void CalcMaterialMoney()
        {
            decimal price = 0;
            decimal netWeight = 0;
            decimal totalMoney = 0;
            //不管磅单是显示或者 不显示 都要计算 
            if (this.TempPriceTb.Visibility == Visibility.Visible)
            {
                try
                {
                    price = Convert.ToDecimal(this.TempPriceTb.Text.Trim());
                }
                catch (Exception ex)
                {
                    //Growl.Error("输入的单价不正确：" + ex.Message, "main");
                    Console.WriteLine("输入的单价不正确：" + ex.Message, "main");
                }
            }

            if (!this.netWeightTb.Text.IsNullOrEmpty())
            {
                try
                {
                    netWeight = Convert.ToDecimal(this.netWeightTb.Text.Trim());
                }
                catch (Exception)
                {
                }
            }


            if (this.TotalMoneyTb.Visibility == Visibility.Visible)
            {
                totalMoney = (decimal)Math.Round((double)(price * netWeight), 3, MidpointRounding.AwayFromZero);

                this.TotalMoneyTb.Text = totalMoney + "";
            }

            if (this.ReceiveMoneyTb.Visibility == Visibility.Visible)
            {
                string receiveMoneyStr = this.ReceiveMoneyTb.Text.Trim();
                if (receiveMoneyStr.IsNullOrEmpty() || receiveMoneyStr.Equals("0")
                    || receiveMoneyStr.Equals("0.0")
                    || receiveMoneyStr.Equals("0.00")
                    || receiveMoneyStr.Equals("0.000"))
                {
                    this.ReceiveMoneyTb.Text = totalMoney + "";
                }

                decimal receiveMoney = 0;
                try
                {
                    receiveMoney = Convert.ToDecimal(receiveMoneyStr);
                }
                catch (Exception)
                {
                }
                if (receiveMoney > totalMoney)
                {
                    this.ReceiveMoneyTb.Text = totalMoney + "";
                }
            }

        }


        private void GetPriceValue()
        {
            //不管磅单是显示或者 不显示 都要计算 
            decimal price = 0;
            decimal receiveMoney = 0;
            if (!this.TempPriceTb.Text.IsNullOrEmpty())
            {
                try
                {
                    price = Convert.ToDecimal(this.TempPriceTb.Text.Trim());
                }
                catch (Exception ex)
                {
                    Console.WriteLine("输入的单价不正确：" + ex.Message, "main");
                }
            }

            var totalMoney = (decimal)Math.Round((double)(price * mWeighingBill.netWeight ?? 0), 3, MidpointRounding.AwayFromZero);
            mWeighingBill.totalMoney = totalMoney;
            mWeighingBill.price = price;
            mWeighingBill.priceId = 0;
            string receiveMoneyStr = this.ReceiveMoneyTb.Text.Trim();
            if (!receiveMoneyStr.IsNullOrEmpty())
            {
                try
                {
                    receiveMoney = Convert.ToDecimal(receiveMoneyStr);
                }
                catch (Exception ex)
                {

                }
                mWeighingBill.receiveMoney = receiveMoney;
            }

            if (this.MoneyTypeCb.Visibility == Visibility.Visible)
            {
                mWeighingBill.moneyType = this.MoneyTypeCb.SelectedIndex;
            }
            else
            {
                mWeighingBill.moneyType = 0;
            }

        }

        #endregion

        #region 模拟数据

        private void MoniWeighingCb_Checked(object sender, RoutedEventArgs e)
        {
            StartMoniTimer();
        }

        private void MoniWeighingCb_UnChecked(object sender, RoutedEventArgs e)
        {
            StopMoniTimer();
        }

        private DispatcherTimer moniDispatcherTimer;

        private void StartMoniTimer()
        {
            if (moniDispatcherTimer == null)
            {
                moniDispatcherTimer = new DispatcherTimer();
                moniDispatcherTimer.Tick += (sender, args) =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        double tonner;
                        bool isbig = this.isGrossRb.IsChecked == true;
                        tonner = CommonFunction.RandomTonner(isbig);
                        CommonFunction.SetTonner(tonner);
                    });
                };
                moniDispatcherTimer.Interval = TimeSpan.FromSeconds(1.1);
            }
            moniDispatcherTimer.Start();
        }

        private void StopMoniTimer()
        {
            moniDispatcherTimer?.Stop();
        }
        #endregion


        #region Custom input item

        private void InitInputUi()
        {

            UpdateTypeButton();

            var dic = DataGridColumnsHelper.GetByName(DataGridColumnsHelper.SimpleModeUI);

            var panel = this.inputStackPanel;

            if (dic.Count > 0)
            {
                foreach (var tc in dic)
                {
                    string key = tc.Key;
                    var item = GetChildControl(panel, key);
                    if (item != null)
                    {
                        if (dic.Keys.Contains(key))
                        {
                            if (dic[key] == true)
                            {
                                item.Visibility = Visibility.Visible;
                            }
                            else
                            {
                                item.Visibility = Visibility.Collapsed;
                            }
                        }
                        else
                        {
                            item.Visibility = Visibility.Collapsed;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 更新过磅类型 按键
        /// </summary>
        private void UpdateTypeButton()
        {
            this.isGrossRb.IsChecked = false;
            this.isTraceRb.IsChecked = false;
            if (App.Config.WeighingConfig.Times == 2)
            {
                this.isGrossRb.Visibility = Visibility.Visible;
                this.isTraceRb.Visibility = Visibility.Visible;
                this.weighingTypePanel.Visibility = Visibility.Collapsed;
            }
            else
            {
                if (App.Config.WeighingConfig.InIgnoreTraeWeighing)
                {
                    this.isGrossRb.Visibility = Visibility.Collapsed;
                    this.isTraceRb.Visibility = Visibility.Collapsed;
                    this.weighingTypePanel.Visibility = Visibility.Visible;
                    this.weighingTypeText.Text = "一次过磅不计皮重";
                }
                else
                {
                    this.isGrossRb.Visibility = Visibility.Collapsed;
                    this.isTraceRb.Visibility = Visibility.Collapsed;
                    this.weighingTypePanel.Visibility = Visibility.Visible;
                    this.weighingTypeText.Text = "一次过磅";
                }
            }
        }

        /// <summary>
        /// 递归 Get Child Control
        /// </summary>
        /// <param name="panel"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private Control GetChildControl(Panel panel, string name)
        {
            foreach (var item in panel.Children)
            {

                if (item is Panel p)
                {
                    var child = GetChildControl(p, name);
                    if (child != null)
                    {
                        return child;
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (item is TextBox tb)
                {
                    Console.WriteLine(tb.Name);
                    if (tb.Name.Equals(name))
                    {
                        return tb;
                    }
                }
                else if (item is ComboBox comboBox)
                {
                    Console.WriteLine(comboBox.Name);
                    if (comboBox.Name.Equals(name))
                    {
                        return comboBox;
                    }
                }
            }
            return null;
        }
        #endregion

        #region 自定义界面

        private Dictionary<Int32, Control> _uiDics;
        private Dictionary<Int32, Control> UiDics
        {
            get
            {
                if (_uiDics == null || _uiDics.Count <= 0)
                {
                    var style = FindResource("CheckBoxBaseStyle") as Style;
                    _uiDics = new Dictionary<int, Control>();
                    var cb = new CheckBox()
                    {
                        Style = style,
                        Content = "过磅员",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.userTb.Name,
                        IsChecked = this.userTb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 20, 20, 5),
                    };
                    _uiDics.Add(0, cb);

                    var carNumberCb = new CheckBox()
                    {
                        Style = style,
                        Content = "车牌号",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.carNumberCb.Name,
                        IsChecked = this.carNumberCb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    _uiDics.Add(1, carNumberCb);

                    var drivercb = new CheckBox()
                    {
                        Style = style,
                        Content = "驾驶员",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.driverTb.Name,
                        IsChecked = this.driverTb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    _uiDics.Add(2, drivercb);

                    var phonecb = new CheckBox()
                    {
                        Style = style,
                        Content = "联系电话",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.phoneTb.Name,
                        IsChecked = this.phoneTb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    _uiDics.Add(3, phonecb);


                    var sendcb = new CheckBox()
                    {
                        Style = style,
                        Content = "发货公司",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.sendCompanyCb.Name,
                        IsChecked = this.sendCompanyCb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    _uiDics.Add(4, sendcb);


                    var receivecb = new CheckBox()
                    {
                        Style = style,
                        Content = "收货公司",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.RecevieCompanyCb.Name,
                        IsChecked = this.RecevieCompanyCb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    _uiDics.Add(5, receivecb);


                    var materialCb = new CheckBox()
                    {
                        Style = style,
                        Content = "货物名称",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.materialCb.Name,
                        IsChecked = this.materialCb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    _uiDics.Add(6, materialCb);

                    var grossCb = new CheckBox()
                    {
                        Style = style,
                        Content = "毛重",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.grossWeightTb.Name,
                        IsChecked = this.grossWeightTb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    _uiDics.Add(7, grossCb);


                    var traeCb = new CheckBox()
                    {
                        Style = style,
                        Content = "皮重",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.TraeWeightTb.Name,
                        IsChecked = this.TraeWeightTb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    _uiDics.Add(8, traeCb);

                    var pricecb = new CheckBox()
                    {
                        Style = style,
                        Content = "单价",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.TempPriceTb.Name,
                        IsChecked = this.TempPriceTb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    _uiDics.Add(9, pricecb);

                    var moneycb = new CheckBox()
                    {
                        Style = style,
                        Content = "金额",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.TotalMoneyTb.Name,
                        IsChecked = this.TotalMoneyTb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    _uiDics.Add(10, moneycb);

                    var getmoneycb = new CheckBox()
                    {
                        Style = style,
                        Content = "实收",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.ReceiveMoneyTb.Name,
                        IsChecked = this.ReceiveMoneyTb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    _uiDics.Add(11, getmoneycb);

                    var moneytypecb = new CheckBox()
                    {
                        Style = style,
                        Content = "支付",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.MoneyTypeCb.Name,
                        Margin = new Thickness(20, 5, 20, 5),
                        IsChecked = this.MoneyTypeCb.Visibility == Visibility.Visible,
                    };
                    _uiDics.Add(12, moneytypecb);

                    var remarkCb = new CheckBox()
                    {
                        Style = style,
                        Content = "备注",
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                        Tag = this.remarkCb.Name,
                        IsChecked = this.remarkCb.Visibility == Visibility.Visible,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    _uiDics.Add(13, remarkCb);
                }
                bool backbtnisExist = false;
                string btnName = "backupBtn";
                foreach (var item in _uiDics)
                {
                    if (item.Value is CheckBox cb)
                    {
                        cb.Checked += ColumnCheckBox_Checked;
                        cb.Unchecked += ColumnCheckBox_Unchecked;
                    }
                    else
                    {
                        if (item.Value is Button btn)
                        {
                            backbtnisExist = btn.Name.Equals(btnName);
                        }
                    }
                }
                if (!backbtnisExist)
                {
                    Button backbtn = new Button()
                    {
                        Content = "备用字段",
                        Name = btnName,
                        Width = 120,
                        Height = 30,
                        Margin = new Thickness(20, 10, 20, 10),
                        Style = FindResource("ButtonPrimary") as Style,
                    };
                    var geo = FindResource("settingGeomety") as Geometry;
                    IconElement.SetGeometry(backbtn, geo);
                    IconElement.SetWidth(backbtn, 18);
                    IconElement.SetHeight(backbtn, 18);
                    backbtn.Click += (sender, e) =>
                    {
                        new AddBackupFieldWin()
                        {
                            BillType = WeightingBillType.Mixture,
                            Owner = App.Current.MainWindow,
                        }.Show();
                    };
                    _uiDics.Add(_uiDics.Count + 1, backbtn);
                }

                return _uiDics;
            }
        }
        private void UISettingBtn_Click(object sender, RoutedEventArgs e)
        {
            this.customUiPanel.Children.Clear();
            foreach (var item in UiDics)
            {
                this.customUiPanel.Children.Add(item.Value);
            }
            this.CustomUiPopup.IsOpen = !this.CustomUiPopup.IsOpen;
            this.CustomUiPopup.HorizontalOffset = 0 - (this.customUiPanel.ActualWidth / 2);
        }
        private void ColumnCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (!IsLoaded) return;
            if (sender is CheckBox cb)
            {
                var key = cb.Tag.ToString();
                SaveColumnSetting(key, true);

                var child = GetChildControl(this.inputStackPanel, key);
                if (child != null)
                {
                    child.Visibility = Visibility.Visible;
                }
            }
        }

        private void ColumnCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (!IsLoaded) return;
            if (sender is CheckBox cb)
            {
                var key = cb?.Tag?.ToString() ?? "";
                SaveColumnSetting(key, false);
                var child = GetChildControl(this.inputStackPanel, key);
                if (child != null)
                {
                    child.Visibility = Visibility.Collapsed;
                }
            }
        }

        protected void SaveColumnSetting(string header, bool isShow)
        {
            DataGridColumnsHelper.Save(DataGridColumnsHelper.SimpleModeUI, header, isShow);
        }

        #endregion

        private void SaveFontBtn_Click(object sender, RoutedEventArgs e)
        {
            var oldFontSize = App.Config.OtherConfig.SimpleWeighingUiFontSize;
            string info = "字体大小14 到 20之间";
            var text = this.FontTb.Text;
            int fontsize = 0;
            try
            {
                fontsize = Convert.ToInt32(text);
            }
            catch (Exception)
            {
                Growl.Error(info, "main");
                return;
            }
            if (fontsize.IsBetween(13, 20))
            {
                if (fontsize != oldFontSize)
                {
                    App.Config.OtherConfig.SimpleWeighingUiFontSize = fontsize;
                    var res = CommonFunction.UpdateAppConfig(nameof(OtherConfig));
                    if (res > 0)
                    {
                        UpdateUIFontSize();
                    }
                    else
                    {
                        Growl.Clear();
                        Growl.Error("保存失败，请重试", "main");
                    }
                }
            }
            else
            {
                Growl.Clear();
                Growl.Error(info, "main");
            }
        }

        private void UpdateUIFontSize()
        {
            int fontSize = App.Config.OtherConfig.SimpleWeighingUiFontSize;
            this.FontTb.Text = fontSize + "";
            this.minToneTb.Text = App.Config.WeighingConfig.MixedValidTone.ToString();
            var childs = this.inputStackPanel.Children;
            foreach (var child in childs)
            {
                if (child is ComboBox cb)
                {
                    cb.FontSize = fontSize;
                }
                else if (child is TextBox tb)
                {
                    tb.FontSize = fontSize;
                }
                else
                {
                    if (child is StackPanel stackPanel)
                    {
                        var suns = stackPanel.Children;
                        foreach (var s in suns)
                        {
                            if (s is ComboBox combo)
                            {
                                combo.FontSize = fontSize;
                            }
                            else if (s is TextBox textBox)
                            {
                                textBox.FontSize = fontSize;
                            }
                            else
                            {
                                //nothing to do 
                            }
                        }
                    }
                }
            }
            this.carNumberCb.FontSize = fontSize;
        }

        #region 次数设置
        private void OnceRb_Checked(object sender, RoutedEventArgs e)
        {
            if (App.Config.WeighingConfig.Times == 1) return;
            App.Config.WeighingConfig.Times = 1;
            CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
            UpdateTypeButton();
        }

        private void TwiceRb_Checked(object sender, RoutedEventArgs e)
        {
            if (App.Config.WeighingConfig.Times == 2) return;
            App.Config.WeighingConfig.Times = 2;
            CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
            UpdateTypeButton();
        }
        #endregion

        #region 不计皮重

        private void IgnoreTraeWeightCb_Checked(object sender, RoutedEventArgs e)
        {
            if (isSetDefaultValue) return;
            App.Config.WeighingConfig.InIgnoreTraeWeighing = true;
            CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
            DelegeteFactory.Instance.OnWeighingConfigChanged?.Invoke(App.Config.WeighingConfig);
            UpdateTypeButton();
        }

        private void IgnoreTraeWeightCb_Unchecked(object sender, RoutedEventArgs e)
        {
            if (isSetDefaultValue) return;
            App.Config.WeighingConfig.InIgnoreTraeWeighing = false;
            CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
            DelegeteFactory.Instance.OnWeighingConfigChanged?.Invoke(App.Config.WeighingConfig);
            UpdateTypeButton();
        }


        #endregion

        #region     磅单编号
        private void billnumberTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.backFieldPanel.Children.Count == 0) return;
            setKunNumber();
        }

        private void setKunNumber()
        {
            if (this.backFieldPanel.Children.Count == 0) return;

            for (int i = 0; i < this.backFieldPanel.Children.Count; i++)
            {
                if (this.backFieldPanel.Children[i] is TextBox child)
                {
                    var title = InfoElement.GetTitle(child);
                    if (title == "捆号")
                    {
                        //截取后两位
                        child.Text = billnumberTb.Text.Substring(billnumberTb.Text.Length - 2);
                    }
                    else if (title == "日期")
                    {
                        child.Text = DateTime.Now.ToString(Constant.DateNumberFormat);
                    }
                }
                else
                {
                    if (this.backFieldPanel.Children[i] is ComboBox cb)
                    {
                        var title = InfoElement.GetTitle(cb);
                        if (title == "捆号")
                        {
                            //截取后两位
                            cb.Text = billnumberTb.Text.Substring(billnumberTb.Text.Length - 2);
                        }
                        else if (title == "日期")
                        {
                            if (string.IsNullOrEmpty(cb.Text))
                            {
                                cb.Text = DateTime.Now.ToString(Constant.DateNumberFormat);
                            }
                        }
                    }
                }

            }
        }
        #endregion

        /// <summary>
        /// 保存 最小有效吨位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveMinToneBtn_Click(object sender, RoutedEventArgs e)
        {
            var text = this.minToneTb.Text;
            if (string.IsNullOrEmpty(text))
            {
                MessageBox.Show("请输入正确的有效吨位(数字)");
                return;
            }
            var mintone = 0.0;
            try
            {
                mintone = Convert.ToDouble(text);
                App.Config.WeighingConfig.MixedValidTone = new decimal(mintone);
                CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
            }
            catch (Exception)
            {
                MessageBox.Show("请输入正确的有效吨位(数字)");
            }
        }

    }
}
